package com.example.testapp.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.study.NewsDetailActivity;
import com.example.testapp.activity.adapter.HotsNewAdapter;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.model.NewsItem;
import com.example.testapp.activity.util.LogUtil;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 最新的新闻资讯碎片
 * Created by l on 2016/8/25.
 */
public class HotsNewFragment extends BaseFragment {

    private View view;
    private PullToRefreshListView  mHotNewsList;
    private HotsNewAdapter  newsAdapter;
    private List<NewsItem>  newsItems = new ArrayList<>();
    private static String URL_PATH = "http://wcf.open.cnblogs.com/news/hot/40";
    private boolean flag = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_hots_new, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHotNewsList = (PullToRefreshListView)view.findViewById(R.id.hots_news_list);
        setUpPullToList();
        loadHotsNewsInfo(false);
    }

    /**
     * 设置listview的下拉刷新
     */
    private void setUpPullToList() {
        newsAdapter = new HotsNewAdapter(mContext, newsItems);
        mHotNewsList.setAdapter(newsAdapter);
        mHotNewsList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                 if(refreshView.isHeaderShown()){
                     flag = false;
                     loadHotsNewsInfo(true);
                 }
            }
        });

        mHotNewsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  NewsItem  item = newsItems.get(position - 1);
                  Intent  intent = new  Intent(mContext, NewsDetailActivity.class);
                  Bundle args = new Bundle();
                  args.putSerializable("item", item);
                  intent.putExtras(args);
                  startActivity(intent);
            }
        });
    }

    /**
     * 加载热门新闻的数据
     * @param clean
     */
    private void loadHotsNewsInfo(final boolean clean) {
        AsyncHttpUtil.get(URL_PATH, new AsyncHttpResponseHandler(){

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                mHotNewsList.onRefreshComplete();

                try {
                     if(clean){
                         newsItems.clear();
                     }
                    ByteArrayInputStream bis = new ByteArrayInputStream(responseBody);
                    parseHotsNewsXml(bis);
                    newsAdapter.notifyDataSetChanged();
                }catch (Exception e){
                    e.printStackTrace();
                    LogUtil.d("error", "hots news XmlPullParserException error");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    /**
     * 解析热门新闻
     * @param is
     * @throws IOException
     * @throws XmlPullParserException
     */
    private void parseHotsNewsXml(InputStream is) throws XmlPullParserException, IOException {
        XmlPullParser parser = Xml.newPullParser();

        parser.setInput(is, "UTF-8");
        int event = parser.getEventType();
        NewsItem item = null;

        while (event != XmlPullParser.END_DOCUMENT){
            switch (event){
                case XmlPullParser.START_DOCUMENT:
                    break;
                case XmlPullParser.START_TAG:
                    if("entry".equals(parser.getName())){
                        flag = true;
                        item =  new NewsItem();
                    }
                    if(flag){
                        if("id".equals(parser.getName())){
                            String  id = parser.nextText();
                            item.setId(id);
                        }else if("title".equals(parser.getName())){
                            String title = parser.nextText();
                            item.setTitle(title);
                        }else if("summary".equals(parser.getName())){
                            String summary = parser.nextText();
                            item.setSummary(summary);
                        }else if("published".equals(parser.getName())){
                            String published = parser.nextText();
                            item.setPublished(published);
                        }else if("updated".equals(parser.getName())){
                            String updated = parser.nextText();
                            item.setUpdated(updated);
                        }else if("link".equals(parser.getName())){
                            String link = parser.nextText();
                            item.setLink(link);
                        }else if("diggs".equals(parser.getName())){
                            String diggs = parser.nextText();
                            item.setDiggs(diggs);
                        }else if("views".equals(parser.getName())){
                            String views = parser.nextText();
                            item.setViews(views);
                        }else if("comments".equals(parser.getName())){
                            String comments = parser.nextText();
                            item.setComments(comments);
                        }else if("sourceName".equals(parser.getName())){
                            String sourceName = parser.nextText();
                            item.setSourceName(sourceName);
                        }
                    }
                    break;
                case XmlPullParser.TEXT:
                    break;
                case XmlPullParser.END_TAG:
                    if("entry".equals(parser.getName())){
                        newsItems.add(item);
                    }
                    break;
            }
            event = parser.next();
        }
    }
}
